package com.car.slave.im.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.car.slave.im.model.command.IMLoginMessage;

public class IMLoginStateUtil {
	
	/**
	 * 获取用户唯一标示.
	 * @return
	 */
	public static String getUin(Context context) {
		String sUin = "游客";
		IMLoginMessage msg = restoreLoginMessage(context);
		if (null != msg) {
			sUin = msg.uin;
		}
		return sUin;
	}

	/**
	 * 获取本地登陆的用户信息.
	 * @param context
	 * @return
	 */
	public static IMLoginMessage restoreLoginMessage(Context context) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		String uin = preferences.getString("uin", "");
		if (TextUtils.isEmpty(uin)) {
			return null;
		}
		String token = preferences.getString("token", "");
		String clientId = preferences.getString("clientId", "");
		String nick = preferences.getString("nick", "");
		String pic = preferences.getString("pic", "");
		String address = preferences.getString("address", "");
		String clientVer = preferences.getString("clientVer", "");
		String channel = preferences.getString("channel", "");
		IMLoginMessage initMessage = new IMLoginMessage(uin, token, clientId, nick, pic, address, clientVer, channel);
		return initMessage;
	}

	/**
	 * 保存用户信息到本地.
	 * @param context
	 * @param initMessage
	 */
	public static void saveLoginMessage(Context context, IMLoginMessage initMessage) {
		final SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
		editor.putString("uin", initMessage.uin);
		editor.putString("token", initMessage.token);
		editor.putString("clientId", initMessage.clientId);
		editor.putString("nick", initMessage.nick);
		editor.putString("pic", initMessage.pic);
		editor.putString("address", initMessage.address);
		editor.putString("clientVer", initMessage.clientVer);
		editor.putString("channel", initMessage.channel);
		editor.commit();
	}
	
	/**
	 * 清楚本地保存的登陆信息
	 * @param context
	 */
	public static void clearLoginMessage(Context context) {
		final SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
		editor.remove("uin").remove("token").remove("clientId").remove("nick").
		remove("pic").remove("address").remove("clientVer").remove("channel");
		editor.commit();
	}
}
